<?php
/**
 * 配置读取
 * @author yangdongqi <yangdongqi@hayzone.com>
 */
class CConfigReader extends CComponent {
	
	/**
	 * 根目录alias
	 * @var string
	 */
	public $baseAlias = 'application.config';
	
	/**
	 * 根目录
	 * @var string
	 */
	protected $_basePath;
	
	public function init() {}
	
	/**
	 * 获取根目录
	 * Enter description here ...
	 */
	public function getBasePath() {
		if(!$this->_basePath) {
			$this->_basePath = Yii::getPathOfAlias($this->baseAlias);
		}
		return $this->_basePath;
	}
	
	/**
	 * 读取数据
	 * Enter description here ...
	 * @param unknown_type $rpath
	 * @param unknown_type $content = array()
	 */
	public function read($rpath, $context = array()) {
		if(file_exists($this->getFilePath($rpath))) {
			return $this->readRecursive(
				$this->getFileData($rpath, $context), 
				$context
			);
		}
		return array();
	}
	
	/**
	 * 获取文件数据
	 * Enter description here ...
	 * @param unknown_type $rpath
	 */
	public function getFileData($rpath, &$context = array()) {
		extract($context);
		return include $this->getFilePath($rpath);
	}
	
	/**
	 * 获取文件路径
	 * Enter description here ...
	 * @param unknown_type $rpath
	 */
	public function getFilePath($rpath) {
		return $this->getBasePath() . DIRECTORY_SEPARATOR .
		str_replace('.', DIRECTORY_SEPARATOR, $rpath) . '.php';
	}
	
	/**
	 * 合并文件
	 * Enter description here ...
	 * @param unknown_type $data
	 */
	protected function readRecursive($data, &$context = array()) {
		if(!isset($data['_import'])) return $data;
		$copied = $data;
		$import = $copied['_import'];
		foreach($import as $k=>$one) {
			$allMatch = false;
			$dataIsSet = true;
			
			list($selfNodePath, $target) = $one;
			list($filePath, $nodePath) = explode('//', $target);
			$nodes = explode('.', $nodePath);
			$nodeData = $this->readRecursive($this->getFileData($filePath, $context), $context);
			
			foreach($nodes as $node) {
				if($node == '*') {
					$allMatch = true;
					break;
				}
				$nodeData = $nodeData[$node];
			}
			
			$selfNodes = explode('.', $selfNodePath);
			$selfData = &$copied;
			
			foreach($selfNodes as $node) {
				if($node == '*') {
					$allMatch = true;
					break;
				}
				$dataIsSet = isset($selfData[$node]);
				$selfData = &$selfData[$node];
			}
			if($allMatch) {
				foreach($nodeData as $k=>$v) {
					$dataIsSet = isset($selfData[$k]);
					$selfData[$k] = @$this->mergeData($nodeData[$k], $selfData[$k], $dataIsSet);
				}
			} else {
				$nodeData = @$this->mergeData($nodeData, $selfData, $dataIsSet);
			}
		}
		
		unset($copied['_import']);
		return $copied;
	}
	
	/**
	 * 合并数据
	 * Enter description here ...
	 * @param unknown_type $data1
	 * @param unknown_type $data2
	 */
	protected function mergeData($data1, $data2, $dataIsSet = false) {
		if(is_array($data1)) {
			 $data2 = array_merge($data1, is_array($data2) ? $data2 : array());
		} elseif(!$dataIsSet) {
			$data2 = $data1;
		}
		return $data2;
	}

}

?>